import MsgHub from "./msg_hub";

export default class Helper {
    static getStrLength(str: string) {
        var len = 0;
        for (let i = 0; i < str.length; i++) {
            if (/^[\u4e00-\u9fa5]+$/.test(str[i])) { //检查中文
                len += 2;
            }
            else {
                len++;
            }
        }
        return len;
    }
    static cutStr(str: string, maxLen: number) {
        var dst = "";
        var len = 0;
        for (let i = 0; i < str.length; i++) {
            if (/^[\u4e00-\u9fa5]+$/.test(str[i])) { //检查中文
                len += 2;
            }
            else {
                len++;
            }

            if (len > maxLen) {
                break;
            }

            dst += str[i];
        }
        return dst;
    }

    static isLeapYear(year: number) {
        if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {
            return (true);
        } else { return (false); }
    }

    static getImageBase64(img: any) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var dataURL = canvas.toDataURL();
        return dataURL;
    }

    static base64ToTexture(base64: string) {
        return new Promise<cc.Texture2D>((resolve, reject) => {
            var img = document.createElement("img");
            img.src = base64;
            img.onload = () => {
                let tex = new cc.Texture2D();
                tex.initWithElement(img);
                resolve(tex);
            };

            img.onerror = () => {
                reject("图片加载失败");
            };
        });
    }
    static checkMobile(str: string) {
        if (!(/^1[3|4|5|6|7|8][0-9]\d{4,8}$/.test(str))) {
            return false;
        }
        return true;
    }
    static req(type: string, url: string, data: any, notProcessFail: boolean) {
        // return new Promise<any>((resolve, reject) => {
        //     $.ajax({
        //         type: type,
        //         url: url,
        //         data: data,
        //         success: (data: any, textStatus: any, jqXHR: any) => {
        //             if (data.code) {
        //                 var box = null;
        //                 if (!notProcessFail) {
        //                     box = Helper.showErrBox(data);
        //                 }
        //                 reject(data);
        //                 return;
        //             }
        //             resolve(data);
        //         },
        //         error: (e: any) => {
        //             //错误
        //             console.log(`ajax:${url},error:`, e);
        //             var box = null;
        //             if (!notProcessFail) {
        //                 box = Helper.processFail(e);
        //             }
        //             var data = e.responseJSON;
        //             reject(data);
        //         }
        //     });
        // });
    }
    static processFail(e: any) {
        let msg: any = {};
        switch (e.status) {
            case 400:
                var data = e.responseJSON;
                return Helper.showErrBox(data);
                break;
            case 500:
                //错误
                msg.text = `系统错误`;
                break;
            default:
                //错误
                msg.text = `网络错误，请稍后再试，代码：${e.status}`;
                break;
        }
        MsgHub.emit("msg_box", msg);
        return msg.handle;
    }

    static showErrBox(data: any) {
        let msg: any = {};
        switch (data.code) {
            case 10002:
                msg.text = "用户没有奖品可以领取";
                break;
            case 10003:
                msg.text = "用户领取奖品方式错误";
                break;
            case 10004:
                msg.text = "用户已领取奖品";
                break;
            case 0:
                return;
        }
        MsgHub.emit("msg_box", msg );
        return msg.handle;
    }

    static shot(targetNode: cc.Node, camera: cc.Camera) {
        let node = new cc.Node();
        node.parent = targetNode;
        node.setPosition(0, 0);

        camera.enabled = false;
        // 新建一个 RenderTexture，并且设置 camera 的 targetTexture 为新建的 RenderTexture，这样 camera 的内容将会渲染到新建的 RenderTexture 中。
        let texture = new cc.RenderTexture();
        let gl = cc.game["_renderContext"];
        // 如果截图内容中不包含 Mask 组件，可以不用传递第三个参数
        texture.initWithSize(targetNode.width, targetNode.height, gl.STENCIL_INDEX8);
        camera.targetTexture = texture;

        // 渲染一次摄像机，即更新一次内容到 RenderTexture 中
        camera.render(targetNode);

        return texture;
    }

    static shotToBase64(targetNode: cc.Node, camera: cc.Camera) {
        let texture = this.shot(targetNode, camera);

        // 这样我们就能从 RenderTexture 中获取到数据了
        let data = texture.readPixels();
        // 接下来就可以对这些数据进行操作了
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        canvas.width = texture.width;
        canvas.height = texture.height;

        let width = texture.width;
        let height = texture.height;
        let rowBytes = width * 4;
        for (let row = 0; row < height; row++) {
            let srow = height - 1 - row;
            let imageData = ctx.createImageData(width, 1);
            let start = srow * width * 4;
            for (let i = 0; i < rowBytes; i++) {
                imageData.data[i] = data[start + i];
            }

            ctx.putImageData(imageData, 0, row);
        }
        return canvas.toDataURL("image/jpeg");
    }
};